package fr.unice.polytech.chord.samples.commands;

import fr.unice.polytech.chord.core.Entry;
import fr.unice.polytech.chord.core.Key;
import fr.unice.polytech.chord.core.Tracker;
import fr.unice.polytech.chord.samples.managers.Manager;

/**
 * @author Laurent Pellegrino
 * 
 * @version 10/30/2009
 */
public class PutCommand extends Command {

	/**
	 * Constructor.
	 * 
	 * @param manager
	 *            the manager that will execute this command.
	 */
	public PutCommand(Manager manager) {
		super(manager, "Puts a key/value on the overlay", new String[] { "put",
				"p" }, new String[] { "key", "value" });
	}

	/**
	 * {@inheritDoc}
	 */
	public void execute(String... args) {
		Key key = null;
		try {
			key = new Key(Integer.parseInt(args[0]));
		} catch (Exception e) {
			super.printInfo("Key argument must be a number");
			return;
		}
		Tracker remoteTracker = super.getManager().getTracker();

		if (args.length > 1) {
			if (remoteTracker.getNumberOfPeersManaged() == 0) {
				super.printInfo("There is no peer on the overlay");
			} else if (remoteTracker.getRandomPeer().get(key) != null) {
				super
						.printInfo("The key already exists on the overlay. Please remove it before to add");
			} else {
				String value = "";
				for (int i = 1; i < args.length; i++) {
					value = value.concat(args[i]);
					if (i < args.length - 1) {
						value = value.concat(" ");
					}
				}

				remoteTracker.getRandomPeer()
						.put(new Entry<String>(key, value));

				super.printInfo("(" + key + "," + value
						+ ") has been added on the overlay");
			}
		} else {
			super
					.printInfo("Put operation must have two arguments which are the key and the value to add.");
		}
	}
}
